# coding: utf-8
from wxpy import Bot, Chat
import math
import os
from PIL import Image
 
class WxFriendImage(Chat):
    @staticmethod
    def get_image():
        path = os.path.abspath(".")
        bot = Bot()  # 机器人对象
        friends = bot.friends(update=True)
 
        dirs = path + "\\wxImages"
        if not os.path.exists(dirs):
            os.mkdir("wxImages")
 
        index = 0
        for friend in friends:
            print(f"正在保存{friend.nick_name}的微信头像")
            friend.get_avatar(dirs + "\\" + f"{str(index)}.jpg")
            index += 1
 
        return dirs
 
    @staticmethod
    def composite_image(dirs):
        images_list = os.listdir(dirs)
        images_list.sort(key=lambda x: int(x[:-4]))  # 根据头像名称排序
        length = len(images_list)  # 头像总数
        image_size = 2560
        # 每个头像大小
        each_size = math.ceil(image_size / math.floor(math.sqrt(length)))
        lines = math.ceil(math.sqrt(length))  # 列数
        rows = math.ceil(math.sqrt(length))  # 行数
        image = Image.new('RGB', (each_size * lines, each_size * rows))
        row = 0
        line = 0
        os.chdir(dirs)
        for file in images_list:
            try:
                with Image.open(file) as img:
                    img = img.resize((each_size, each_size))
                    image.paste(img, (line * each_size, row * each_size))
                    line += 1
                    if line == lines:
                        line = 0
                        row += 1
            except IOError:
                print(f"头像{file}异常，请查看")
                continue
        img = image.save(os.getcwd() + "/all.png")
        if not img:
            print('所有的微信头像已合成，请查阅all.png!')
def main():
    dirs = WxFriendImage.get_image()
    WxFriendImage.composite_image(dirs)
if __name__ == '__main__':
    main()